#include "history.h"
#include "ui_history.h"

history::history(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::history)
{
    ui->setupUi(this);

    QString currentDate = QDate::currentDate().toString("yyyy-MM-dd");
    ui->label->setText("日期: " + currentDate);

    // 创建日历
    calendar = new QCalendarWidget(this);
    calendar->setHidden(true);  // 初始时隐藏日历

    calendar->setGeometry(ui->pushButton->geometry().left(),
                              ui->pushButton->geometry().bottom() + 10, // 在按钮下方10像素处
                              calendar->sizeHint().width(),
                              calendar->sizeHint().height());

    connect(calendar, &QCalendarWidget::clicked, this, &history::dateSelected);

    // 初始化模型和列表视图
    model = new QSqlQueryModel(this);
    ui->listView->setModel(model);

    //connect(ui->listView, &QListView::clicked, this, &history::on_listView_clicked);

    // 更新列表视图
    updateListView();

}

history::~history()
{
    delete ui;
}

void history::on_pBtn_back_clicked()
{
    this->hide();
    emit backToMainPage();
}

void history::on_pushButton_clicked()
{
    calendar->setHidden(!calendar->isHidden());
}

void history::dateSelected(const QDate &date) {
    // 在按钮上显示选中的日期
    ui->label->setText("日期: " + date.toString("yyyy-MM-dd"));
    // 隐藏日历
    calendar->setHidden(true);
    // 更新列表视图
    updateListView();
}

void history::updateListView()
{
    QString selectedDate = ui->label->text().split("日期: ").last();
    QString queryStr = QString("SELECT table_name, start_time, end_time FROM meta_data WHERE DATE(start_time) = '%1'").arg(selectedDate);
    QSqlQuery query(queryStr);

    QStringList listData;
    while (query.next()) {
        QString startTime = query.value(1).toDateTime().toString("hh:mm:ss");
        QString endTime = query.value(2).toDateTime().toString("hh:mm:ss");
        listData.append(startTime + " - " + endTime);
    }

    // 创建一个新的标准项模型
    QStandardItemModel *standardModel = new QStandardItemModel(this);

    // 将数据添加到模型中
    for (const QString &data : listData) {
        QStandardItem *item = new QStandardItem(data);
        standardModel->appendRow(item);
    }

    // 设置视图的模型
    ui->listView->setModel(standardModel);

    // 设置列表视图的样式表
    ui->listView->setStyleSheet("font: italic 20pt \"Z003\";");
}



void history::on_listView_clicked(const QModelIndex &index)
{
    QString selectedText = index.data().toString();
    QStringList timeParts = selectedText.split(" - ");
    QString startTime = timeParts.first();
    QString selectedDate = ui->label->text().split("日期: ").last();
    QDateTime startDateTime = QDateTime::fromString(selectedDate + " " + startTime, "yyyy-MM-dd hh:mm:ss");

    QString tableNameQueryStr = QString("SELECT table_name FROM meta_data WHERE start_time = '%1'")
                                    .arg(startDateTime.toString("yyyy-MM-dd hh:mm:ss"));
    QSqlQuery tableNameQuery(tableNameQueryStr);
    QString tableName;
    if (tableNameQuery.next()) {
        tableName = tableNameQuery.value(0).toString();
    }

    qDebug() << "表名：" << tableName;

    plotData(tableName);
}

void history::plotData(const QString &tableName)
{
    // 构建查询语句，从数据库获取数据
    QSqlQuery query(QString("SELECT timestamp, temperature, humidity, illumination FROM %1").arg(tableName));

    // 准备存储数据的容器
    QVector<double> timeData, temperatureData, humidityData, illuminationData;

    // 从查询结果中读取数据
    while (query.next()) {
        QDateTime timestamp = query.value(0).toDateTime();
        double temperature = query.value(1).toDouble();
        double humidity = query.value(2).toDouble();
        double illumination = query.value(3).toDouble();

        // 添加数据到对应的容器中
        timeData.append(timestamp.toSecsSinceEpoch());
        temperatureData.append(temperature);
        humidityData.append(humidity);
        illuminationData.append(illumination);
    }

    // 确保 timeData 容器中有数据
    if (timeData.isEmpty()) {
        return;
    }

    // 获取时间范围
    double timeStart = timeData.first();
    double timeEnd = timeData.last();

    // 清除之前的图形
    ui->widget_1->clearGraphs();
    ui->widget_2->clearGraphs();
    ui->widget_3->clearGraphs();

    // 设置温度折线图
    ui->widget_1->addGraph();
    QCPGraph *temperatureGraph = ui->widget_1->graph(0);
    temperatureGraph->setData(timeData, temperatureData);
    temperatureGraph->setPen(QPen(Qt::red));
    temperatureGraph->setName("Temperature");

    // 配置温度图的x轴
    QSharedPointer<QCPAxisTickerDateTime> timeTicker(new QCPAxisTickerDateTime);
    timeTicker->setDateTimeFormat("hh:mm:ss");
    ui->widget_1->xAxis->setTicker(timeTicker);
    ui->widget_1->xAxis->setTickLabelRotation(45);
    ui->widget_1->axisRect()->setupFullAxesBox();
    ui->widget_1->yAxis->setLabel("Temperature (°C)");
    ui->widget_1->yAxis->setRange(10, 40);
    ui->widget_1->xAxis->setRange(timeStart, timeEnd);

    // 重新绘制温度图
    ui->widget_1->replot();

    // 设置湿度折线图
    ui->widget_2->addGraph();
    QCPGraph *humidityGraph = ui->widget_2->graph(0);
    humidityGraph->setData(timeData, humidityData);
    humidityGraph->setPen(QPen(Qt::blue));
    humidityGraph->setName("Humidity");

    // 配置湿度图的x轴
    ui->widget_2->xAxis->setTicker(timeTicker);
    ui->widget_2->xAxis->setTickLabelRotation(45);
    ui->widget_2->axisRect()->setupFullAxesBox();
    ui->widget_2->yAxis->setLabel("Humidity (%RH)");
    ui->widget_2->yAxis->setRange(0, 100);
    ui->widget_2->xAxis->setRange(timeStart, timeEnd);

    // 重新绘制湿度图
    ui->widget_2->replot();

    // 设置光照度折线图
    ui->widget_3->addGraph();
    QCPGraph *illuminationGraph = ui->widget_3->graph(0);
    illuminationGraph->setData(timeData, illuminationData);
    illuminationGraph->setPen(QPen(Qt::green));
    illuminationGraph->setName("Illumination");

    // 配置光照度图的x轴
    ui->widget_3->xAxis->setTicker(timeTicker);
    ui->widget_3->xAxis->setTickLabelRotation(45);
    ui->widget_3->axisRect()->setupFullAxesBox();
    ui->widget_3->yAxis->setLabel("Illumination (Lux)");
    ui->widget_3->yAxis->setRange(0, 2000);
    ui->widget_3->xAxis->setRange(timeStart, timeEnd);

    // 重新绘制光照度图
    ui->widget_3->replot();
}


